package com.h3bpm.starcharge.service.impl.k3c;

import OThinker.H3.Entity.DataModel.BizObject;
import OThinker.H3.Entity.Instance.Data.InstanceData;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.h3bpm.starcharge.common.bean.RestfulErrorCode;
import com.h3bpm.starcharge.common.bean.RetResult;
import com.h3bpm.starcharge.common.uitl.DateUtil;
import com.h3bpm.starcharge.common.uitl.FileUtil;
import com.h3bpm.starcharge.common.uitl.k3c.K3cUtil;
import com.h3bpm.starcharge.config.K3CloundConfig;
import com.h3bpm.starcharge.ret.k3c.K3cBase;
import com.h3bpm.starcharge.service.k3c.K3cService;
import com.h3bpm.starcharge.service.k3c.PaymentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * @author LLongAgo
 * @date 2019/4/22
 * @since 1.0.0
 */
@Service
public class PaymentServiceImpl implements PaymentService {

    @Autowired
    private K3cUtil util;
    @Autowired
    private K3cService k3cService;
    @Autowired
    private K3CloundConfig k3CloundConfig;
    @Value("${k3c_dbId}")
    private String dbId;
    @Value("${k3c_uid}")
    private String uid;
    @Value("${k3c_pwd}")
    private String pwd;
    @Value("${k3c_lang}")
    private int lang;
    /**
     * 付款申请单
     */
    private static final String PAYAPPLY_FORM_ID = "CN_PAYAPPLY";

    /**
     * 电费预付
     * @param instanceData InstanceData
     * @return RetResult
     * @throws Exception
     */
    @Override
    public RetResult electricChargePre(InstanceData instanceData) throws Exception {
        HashMap<String, Object> valueTable = instanceData.getBizObject().getValueTable();
        JSONObject basic = payApplyParam(valueTable);
        JSONObject jsonObject = new JSONObject(true);
        jsonObject.put("formid", PAYAPPLY_FORM_ID);
        jsonObject.put("data", JSON.toJSONString(basic, SerializerFeature.MapSortField));
        // 禁止循环引用
        String param = JSON.toJSONString(jsonObject, SerializerFeature.DisableCircularReferenceDetect);
        String cookie = util.getLoginCookie();
        // 保存
        RetResult result = k3cService.save(k3CloundConfig.getUrl() + k3CloundConfig.getSave(), cookie, param);
        if (!RestfulErrorCode.SUCCESS.getCode().equals(result.getCode())) {
            return result;
        }
        K3cBase k3cBase = (K3cBase) result.getData();
        String submitParam = k3cService.buildParam(PAYAPPLY_FORM_ID, k3cBase.getId(), null, null);
        // 提交
        k3cService.save(k3CloundConfig.getUrl() + k3CloundConfig.getSubmit(), cookie, submitParam);
        // 审核
        k3cService.save(k3CloundConfig.getUrl() + k3CloundConfig.getAudit(), cookie, submitParam);
        return result;
    }

    /**
     * 付款申请单参数
     */
    private JSONObject payApplyParam(HashMap<String, Object> vt) throws Exception {
        // 解析json模板
        String template = FileUtil.readJsonData("k3c/paymentRequisition-save.json");
        JSONObject basic = JSON.parseObject(template);
        JSONObject model = basic.getJSONObject("Model");
        Map<String, Object> billtypeid = new HashMap<>(2);
        billtypeid.put("FNUMBER", vt.get("receiptType"));
        model.put("FBILLTYPEID", billtypeid);
        Date date = (Date) vt.get("applyDate");
        model.put("FDATE", DateUtil.dateToString(date, "yyyy-MM-dd hh:mm:ss"));
        model.put("FCONTACTUNITTYPE", vt.get("payeeType"));
        model.put("FRECTUNITTYPE", vt.get("payeeType"));
        Map<String, Object> contactunit = new HashMap<>(2);
        contactunit.put("FNumber", vt.get("payeeCode"));
        model.put("FCONTACTUNIT", contactunit);
        Map<String, Object> contactunit1 = new HashMap<>(2);
        contactunit1.put("FNumber", vt.get("payeeCode"));
        model.put("FRECTUNIT", contactunit1);
        Map<String, Object> currency = new HashMap<>(2);
        currency.put("FNumber", vt.get("currency"));
        Map<String, Object> currency1 = new HashMap<>(2);
        currency1.put("FNumber", vt.get("currency"));
        model.put("FCURRENCYID", currency);
        model.put("FSETTLECUR", currency1);
        model.put("F_WB_BZ", vt.get("remark"));
        Map<String, Object> org = new HashMap<>(2);
        org.put("FNumber", vt.get("applyOrgCode"));
        Map<String, Object> org1 = new HashMap<>(2);
        org1.put("FNumber", vt.get("applyOrgCode"));
        Map<String, Object> org2 = new HashMap<>(2);
        org2.put("FNumber", vt.get("applyOrgCode"));
        Map<String, Object> org3 = new HashMap<>(2);
        org3.put("FNumber", vt.get("applyOrgCode"));
        model.put("FPAYORGID", org);
        model.put("FSETTLEORGID", org1);
        model.put("FPURCHASEORGID", org2);
        model.put("FAPPLYORGID", org3);
        Map<String, Object> supplier = new HashMap<>(2);
        supplier.put("FNumber", vt.get("payeeCode"));
        model.put("F_WB_Supplier", supplier);
        List<Map<String, Object>> details = new ArrayList<>();
        BizObject[] zbBizObjects = (BizObject[]) vt.get("electricDetail");
        if (null != zbBizObjects && zbBizObjects.length > 0) {
            for (BizObject object : zbBizObjects) {
                HashMap<String, Object> table = object.getValueTable();
                Map<String, Object> electricDetail = new HashMap<>(16);
                Map<String, Object> costid = new HashMap<>(2);
                costid.put("FNUMBER", table.get("costCode"));
                electricDetail.put("FCOSTID", costid);
                Map<String, Object> settletypeid = new HashMap<>(2);
                settletypeid.put("FNumber", table.get("clearType"));
                electricDetail.put("FSETTLETYPEID", settletypeid);
                Map<String, Object> paypurposeid = new HashMap<>(2);
                paypurposeid.put("FNumber", table.get("purpose"));
                electricDetail.put("FPAYPURPOSEID", paypurposeid);
                Map<String, Object> xm = new HashMap<>(2);
                xm.put("FNUMBER", table.get("projectCode"));
                electricDetail.put("F_WB_XM", xm);
                date = (Date) table.get("dueDate");
                electricDetail.put("FENDDATE", DateUtil.dateToString(date, "yyyy-MM-dd hh:mm:ss"));
                date = (Date) table.get("payDate");
                electricDetail.put("FEXPECTPAYDATE", DateUtil.dateToString(date, "yyyy-MM-dd hh:mm:ss"));
                electricDetail.put("FAPPLYAMOUNTFOR", table.get("payMoney"));
                electricDetail.put("FEACHBANKACCOUNT", table.get("bankAccount"));
                electricDetail.put("FEACHCCOUNTNAME", table.get("bankName"));
                electricDetail.put("FEACHBANKNAME", table.get("openingBank"));
                details.add(electricDetail);
            }
        }
        model.put("FPAYAPPLYENTRY", details);
        return basic;
    }
}